package org.example.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

//我的netty服务器
public class NettyServer {

    public static void main(String[] args) {
        //创建模组板 内含注册线程组 和读写线程组
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel)  {
                        socketChannel.pipeline().addLast(new StringDecoder())
                                .addLast(new SimpleChannelInboundHandler<String>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s)  {
                                        System.out.println("解码的消息为 ：" + s);
                                    }
                                });


                        socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));

                    }
                });
        //绑定端口 返回值为异步的
        ChannelFuture channelFuture = serverBootstrap.bind(8080);



        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("端口绑定成功");
            }
        }
        );


    }







}
